package com.chexiehui.jc.ui.activity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.StringUtils;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpActivity;
import com.chexiehui.jc.entity.UserInfo;
import com.chexiehui.jc.event.UserInfoChangeEvent;
import com.chexiehui.jc.mvp.mine.AccountSettingCovenant;
import com.chexiehui.jc.mvp.mine.AccountSettingPresenter;
import com.chexiehui.jc.utils.AliossUtil;
import com.chexiehui.jc.utils.AppCommonUtil;
import com.chexiehui.jc.utils.BundleBuilder;
import com.chexiehui.jc.utils.GlideEngine;
import com.chexiehui.jc.utils.GlideUtil;
import com.chexiehui.jc.utils.SerializableSpTools;
import com.chexiehui.jc.widget.CircleImageView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.style.PictureWindowAnimationStyle;
import com.luck.picture.lib.tools.LocalMediaUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

/**
 * 账号管理
 */
public class AccountSettingActivity extends BaseMvpActivity<AccountSettingPresenter> implements AccountSettingCovenant.View {
    @BindView(R.id.iv_user_head)
    CircleImageView ivUserHead;
    @BindView(R.id.rl_user_head_panel)
    RelativeLayout rlUserHeadPanel;
    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    @BindView(R.id.rl_user_name_panel)
    RelativeLayout rlUserNamePanel;
    @BindView(R.id.tv_user_introduce)
    TextView tvUserIntroduce;
    @BindView(R.id.rl_user_introduce_panel)
    RelativeLayout rlUserIntroducePanel;
    @BindView(R.id.iv_user_background)
    ImageView ivUserBackground;
    @BindView(R.id.rl_user_background_panel)
    RelativeLayout rlUserBackgroundPanel;
    @BindView(R.id.tv_user_phone)
    TextView tvUserPhone;
    @BindView(R.id.rl_user_phone_panel)
    RelativeLayout rlUserPhonePanel;
    @BindView(R.id.rl_set_password_panel)
    RelativeLayout rlSetPasswordPanel;
    @BindView(R.id.rl_weixin_bind_panel)
    RelativeLayout rlWeixinBindPanel;
    @BindView(R.id.rl_weibo_bind_panel)
    RelativeLayout rlWeiboBindPanel;
    @BindView(R.id.rl_delete_account_panel)
    RelativeLayout rlDeleteAccountPanel;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;
    private UserInfo userInfo;

    @Override
    protected void beforeSetView() {
        userInfo = SerializableSpTools.getUserInfo();
    }

    @Override
    protected AccountSettingPresenter createPresenter() {
        return new AccountSettingPresenter(this);
    }

    @Override
    protected void setTitleBar() {
        titleBar.setTitleMainText("账号管理");
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_account_setting;
    }

    @Override
    protected void initView(Bundle var1) {
        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.setEnableLoadMore(false);
        mRefreshLayout.setEnableOverScrollDrag(true);
        GlideUtil.loadImageViewCircleCrop(mContext, userInfo.getPhoto(), ivUserHead, R.drawable.shape_circle, R.drawable.shape_circle);
        GlideUtil.loadImageViewCrop(mContext, userInfo.getBgPhoto(), ivUserBackground, R.drawable.shape_square, R.drawable.shape_square);
        tvUserName.setText(userInfo.getName());
        tvUserIntroduce.setText(userInfo.getRemark());
        tvUserPhone.setText(AppCommonUtil.phoneMask(userInfo.getTel()));
    }

    @OnClick({R.id.rl_user_head_panel, R.id.rl_user_name_panel, R.id.rl_user_introduce_panel, R.id.rl_user_background_panel, R.id.rl_user_phone_panel, R.id.rl_set_password_panel, R.id.rl_weixin_bind_panel})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_user_head_panel:
                applyPhotoPermission(100);
                break;
            case R.id.rl_user_background_panel:
                applyPhotoPermission(200);
                break;
            case R.id.rl_user_name_panel:
                startActivityForResult(InputUsernameActivity.class, 300, new BundleBuilder().putString("oldText", userInfo.getName()).create());
                break;
            case R.id.rl_user_introduce_panel:
                startActivityForResult(InputIntroduceActivity.class, 400, new BundleBuilder().putString("oldText", userInfo.getRemark()).create());
                break;
            case R.id.rl_user_phone_panel:
                startActivity(ChangePhoneActivity.class);
                break;
            case R.id.rl_set_password_panel:
                startActivity(ChangePasswordActivity.class);
                break;
            case R.id.rl_weixin_bind_panel:
                break;
        }
    }

    private void applyPhotoPermission(int typecode) {
        AndPermission.with(this)
                .permission(Permission.CAMERA, Permission.STORAGE)
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                        PictureWindowAnimationStyle windowAnimationStyle = new PictureWindowAnimationStyle();
                        windowAnimationStyle.ofAllAnimation(R.anim.picture_anim_up_in, R.anim.picture_anim_down_out);
                        // 进入相册 以下是例子：不需要的api可以不写
                        PictureSelector.create(mContext)
                                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                                .loadImageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                                .theme(R.style.picture_QQ_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style v2.3.3后 建议使用setPictureStyle()动态方式
                                .setPictureWindowAnimationStyle(windowAnimationStyle)// 自定义相册启动退出动画
                                .isWeChatStyle(false)// 是否开启微信图片选择风格
                                .setLanguage(-1)// 设置语言，默认中文
                                .isWithVideoImage(false)// 图片和视频是否可以同选,只在ofAll模式下有效
                                .maxSelectNum(9)// 最大图片选择数量
                                .minSelectNum(1)// 最小选择数量
                                .maxVideoSelectNum(1) // 视频最大选择数量，如果没有单独设置的需求则可以不设置，同用maxSelectNum字段
                                .minVideoSelectNum(0)// 视频最小选择数量，如果没有单独设置的需求则可以不设置，同用minSelectNum字段
                                .imageSpanCount(4)// 每行显示个数
                                .isReturnEmpty(false)// 未选择数据时点击按钮是否可以返回
                                .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 设置相册Activity方向，不设置默认使用系统
                                .isOriginalImageControl(false)// 是否显示原图控制按钮，如果设置为true则用户可以自由选择是否使用原图，压缩、裁剪功能将会失效
                                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                                .isSingleDirectReturn(true)// 单选模式下是否直接返回，PictureConfig.SINGLE模式下有效
                                .previewImage(true)// 是否可预览图片
                                .previewVideo(true)// 是否可预览视频
                                //.querySpecifiedFormatSuffix(PictureMimeType.ofJPEG())// 查询指定后缀格式资源
                                .enablePreviewAudio(false) // 是否可播放音频
                                .isCamera(true)// 是否显示拍照按钮
                                //.isMultipleSkipCrop(false)// 多图裁剪时是否支持跳过，默认支持
                                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                                //.imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                                .enableCrop(false)// 是否裁剪
                                .cropWH(100, 100)
                                .freeStyleCropEnabled(true)
                                .showCropFrame(true)
                                .compress(true)// 是否压缩
                                .compressQuality(90)// 图片压缩后输出质量 0~ 100
                                .synOrAsy(false)//同步false或异步true 压缩 默认同步
                                .queryMaxFileSize(20)// 只查多少M以内的图片、视频、音频  单位M
                                .isGif(false)// 是否显示gif图片
                                .videoMaxSecond(60)
                                .videoMinSecond(1)
                                .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                                .minimumCompressSize(100)// 小于100kb的图片不压缩
                                .videoQuality(1)// 视频录制质量 0 or 1
                                .recordVideoSecond(60)//录制视频秒数 默认60s
                                .forResult(typecode);//结果回调onActivityResult code*/
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                        if (AndPermission.hasAlwaysDeniedPermission(mContext, deniedPermissions)) {
                            AndPermission.defaultSettingDialog(mContext, Constants.REQUEST_CODE_CARAME).show();
                        } else {
                            showToast(getStringSource(R.string.app_name) + "需要您授权打开相机和相册的权限");
                        }
                    }
                })
                .requestCode(Constants.REQUEST_CODE_CARAME)
                .rationale((requestCode, rationale) -> AndPermission.rationaleDialog(mContext, rationale).show()).start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 100: {
                List<LocalMedia> selectedPhotoList = PictureSelector.obtainMultipleResult(data);
                if (selectedPhotoList.size() > 0) {
                    String path = LocalMediaUtils.getLocalPath(selectedPhotoList.get(0));
                    mvpPresenter.updateAvatar(path);
                }
            }
            break;
            case 200:
                List<LocalMedia> selectedPhotoList = PictureSelector.obtainMultipleResult(data);
                if (selectedPhotoList.size() > 0) {
                    String path = LocalMediaUtils.getLocalPath(selectedPhotoList.get(0));
                    mvpPresenter.updateBackgroundImg(path);
                }
                break;
            case 300:
                if (data != null) {
                    String text = data.getStringExtra("text");
                    if (!StringUtils.isTrimEmpty(text)) {
                        mvpPresenter.updateName(text);
                    }
                }
                break;
            case 400:
                if (data != null) {
                    String text = data.getStringExtra("text");
                    if (!StringUtils.isTrimEmpty(text)) {
                        mvpPresenter.updateRemark(text);
                    }
                }
                break;
        }
    }

    @Override
    public void onUpdateAvatarSuccess(BaseModel<String> successResult) {
        userInfo.setPhoto(AliossUtil.getEndPointFileUrl(successResult.getData()));
        GlideUtil.loadImageViewCircleCrop(mContext, userInfo.getPhoto(), ivUserHead, R.drawable.shape_circle, R.drawable.shape_circle);
        SerializableSpTools.putUserInfo(userInfo);
        EventBus.getDefault().post(new UserInfoChangeEvent());
    }

    @Override
    public void onUpdateAvatarFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public void onUpdateNameSuccess(BaseModel<String> successResult) {
        userInfo.setName(successResult.getData());
        tvUserName.setText(userInfo.getName());
        SerializableSpTools.putUserInfo(userInfo);
        EventBus.getDefault().post(new UserInfoChangeEvent());
    }

    @Override
    public void onUpdateNameFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public void onUpdateRemarkSuccess(BaseModel<String> successResult) {
        userInfo.setRemark(successResult.getData());
        tvUserIntroduce.setText(userInfo.getRemark());
        SerializableSpTools.putUserInfo(userInfo);
        EventBus.getDefault().post(new UserInfoChangeEvent());
    }

    @Override
    public void onUpdateRemarkFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public void onUpdateBackgroundImgSuccess(BaseModel<String> successResult) {
        userInfo.setBgPhoto(AliossUtil.getEndPointFileUrl(successResult.getData()));
        GlideUtil.loadImageViewCrop(mContext, userInfo.getBgPhoto(), ivUserBackground, R.drawable.shape_square, R.drawable.shape_square);
        SerializableSpTools.putUserInfo(userInfo);
        EventBus.getDefault().post(new UserInfoChangeEvent());
    }

    @Override
    public void onUpdateBackgroundImgFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }
}
